<template>
    <div>
        <div class="row mb-1">
            <div class="col ">
                <el-button @click="start" type="primary">查询</el-button>
                <el-button @click="dialogVisible = true; ruleForm = {}" type="primary">+创建</el-button>
            </div>
        </div>
        <el-table :data="tableData" height="65vh" style="width: 100%" @sort-change="sortchange">
            <el-table-column prop="ID" label="ID"></el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="password" label="密码"></el-table-column>
            <el-table-column prop="description" label="备注"></el-table-column>
            <el-table-column prop="createdAt" sortable="custom" :formatter="({ createdAt }) => formatter(createdAt)"
                label="创建时间"></el-table-column>
            <el-table-column label="操作" width="380">
                <template #default="scope">
                    <el-button type="info" @click="v2set(scope.row)">展示设置</el-button>
                    <el-button type="warning" @click="handleClick(scope.row)">修改</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination :hide-on-single-page="true" @current-change="handleCurrentChange" :page-size="Number(limit)"
            layout="prev, pager, next" :total="count"></el-pagination>
        <el-dialog :title="title" v-model="dialogVisible" width="80%">
            <el-form :model="ruleForm" label-width="100px">
                <el-form-item label="名称">
                    <el-input v-model="ruleForm.name"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="ruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="账号">
                    <el-input v-model="ruleForm.phone"></el-input>
                </el-form-item>
                <el-form-item label="organizeid">
                    <el-input v-model="ruleForm.organizeid"></el-input>
                </el-form-item>
                <el-form-item label="家庭">
                    <el-select v-model="ruleForm.home_id" multiple clearable>
                        <el-option v-for="v in homelist" :label="v.name" :value="v.home_id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="ruleForm.description"></el-input>
                </el-form-item>


            </el-form>
            <div class="row">
                <div class="col text-right">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submit">确 定</el-button>
                </div>
            </div>
        </el-dialog>

        <el-dialog title="展示设置" v-model="dialogVisible2" width="80%">
            <el-form :model="ruleFormset" label-width="100px" class="demo-ruleForm">
                <el-form-item label="Title" v-if="ruleForm.v2set">
                    <el-input placeholder="智能设备监控平台" v-model.trim="ruleForm.v2set.title"></el-input>
                </el-form-item>
                <el-form-item label="Logo" v-if="ruleForm.v2set">
                    <el-input v-model.trim="ruleForm.v2set.logo"></el-input>
                </el-form-item>

                <el-form-item label="左侧宽度" v-if="ruleForm.v2set">
                    <el-input-number v-model="ruleForm.v2set.left"></el-input-number>
                </el-form-item>
                <el-form-item label="右侧宽度" v-if="ruleForm.v2set">
                    <el-input-number v-model="ruleForm.v2set.right"></el-input-number>
                </el-form-item>
                <el-form-item label="瀑布行数" v-if="ruleForm.v2set">
                    <el-input-number v-model="ruleForm.v2set.bottom"></el-input-number>
                </el-form-item>
                <el-form-item label="视频">
                    <el-row>
                        <el-col :span="24">
                            <el-button type="primary" @click="addvideo('video')">添加</el-button>
                            <el-button type="danger" @click="removevideo('video')">删除</el-button>
                        </el-col>
                    </el-row>
                    <el-row v-for="v in ruleFormset.video">
                        <el-col :span="24">

                            <el-form-item label="排序">
                                <el-input-number v-model="v.index"></el-input-number>
                            </el-form-item>
                            <el-form-item label="设备">
                                <el-select v-model="v.name">
                                    <el-option v-for="item in list.filter(c => c.category === 'sp')" :key="item.id"
                                        :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="宽度">
                                <el-input-number v-model="v.width"></el-input-number>
                            </el-form-item>
                            <el-form-item label="高度">
                                <el-input-number v-model="v.height"></el-input-number>
                            </el-form-item>
                            <el-form-item label="列数">
                                <el-input-number v-model="v.col"></el-input-number>
                            </el-form-item>
                            <el-form-item label="是否显示">
                                <el-switch v-model="v.show" />
                            </el-form-item>
                            <el-form-item label="显示位置">
                                <el-radio-group v-model="v.Container">
                                    <el-radio label="left">left</el-radio>
                                    <el-radio label="center">center</el-radio>
                                    <el-radio label="right">right</el-radio>
                                    <el-radio label="bottom">bottom</el-radio>
                                </el-radio-group>
                            </el-form-item>


                        </el-col>
                    </el-row>

                </el-form-item>
                <el-form-item label="其他图表">
                    <el-row>
                        <el-col :span="24">
                            <el-button type="primary" @click="addvideo('char')">添加</el-button>
                            <el-button type="danger" @click="removevideo('char')">删除</el-button>
                        </el-col>
                    </el-row>
                    <el-row v-for="v in ruleFormset.char">
                        <el-col :span="24">
                            <el-form-item label="排序">
                                <el-input-number v-model="v.index"></el-input-number>
                            </el-form-item>
                            <el-form-item label="设备">
                                <el-select v-model="v.name">
                                    <el-option v-for="item in list" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="查询状态值">
                                <el-select v-model="v.state" multiple clearable collapse-tags>
                                    <el-option
                                        v-for="item in tuyastate.filter(e => e.name === list.find(c => c.id === v.name)?.category)"
                                        :label="item.dataname" :value="item.code" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="宽度">
                                <el-input-number v-model="v.width"></el-input-number>
                            </el-form-item>
                            <el-form-item label="高度">
                                <el-input-number v-model="v.height"></el-input-number>
                            </el-form-item>
                            <el-form-item label="列数">
                                <el-input-number v-model="v.col"></el-input-number>
                            </el-form-item>
                            <el-form-item label="显示位置">
                                <el-radio-group v-model="v.Container">
                                    <el-radio label="left">left</el-radio>
                                    <el-radio label="center">center</el-radio>
                                    <el-radio label="right">right</el-radio>
                                    <el-radio label="bottom">bottom</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否显示">
                                <el-switch v-model="v.show" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form-item>
                <el-form-item label="设备日志数">
                    <el-col :span="24">
                        <el-form-item label="排序">
                            <el-input-number v-model="ruleFormset.percentage.index"></el-input-number>
                        </el-form-item>
                        <el-form-item label="宽度">
                            <el-input-number v-model="ruleFormset.percentage.width"></el-input-number>
                        </el-form-item>
                        <el-form-item label="高度">
                            <el-input-number v-model="ruleFormset.percentage.height"></el-input-number>
                        </el-form-item>
                        <el-form-item label="列数">
                            <el-input-number v-model="ruleFormset.percentage.col"></el-input-number>
                        </el-form-item>
                        <el-form-item label="显示位置">
                            <el-radio-group v-model="ruleFormset.percentage.Container">
                                <el-radio label="left">left</el-radio>
                                <el-radio label="center">center</el-radio>
                                <el-radio label="right">right</el-radio>
                                <el-radio label="bottom">bottom</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否显示">
                            <el-switch v-model="ruleFormset.percentage.show" />
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="设备概况">
                    <el-col :span="24">
                        <el-form-item label="排序">
                            <el-input-number v-model="ruleFormset.overview.index"></el-input-number>
                        </el-form-item>
                        <el-form-item label="宽度">
                            <el-input-number v-model="ruleFormset.overview.width"></el-input-number>
                        </el-form-item>
                        <el-form-item label="高度">
                            <el-input-number v-model="ruleFormset.overview.height"></el-input-number>
                        </el-form-item>
                        <el-form-item label="列数">
                            <el-input-number v-model="ruleFormset.overview.col"></el-input-number>
                        </el-form-item>
                        <el-form-item label="显示位置">
                            <el-radio-group v-model="ruleFormset.overview.Container">
                                <el-radio label="left">left</el-radio>
                                <el-radio label="center">center</el-radio>
                                <el-radio label="right">right</el-radio>
                                <el-radio label="bottom">bottom</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否显示">
                            <el-switch v-model="ruleFormset.overview.show" />
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="设备日志详情">
                    <el-col :span="24">
                        <el-form-item label="排序">
                            <el-input-number v-model="ruleFormset.log.index"></el-input-number>
                        </el-form-item>
                        <el-form-item label="宽度">
                            <el-input-number v-model="ruleFormset.log.width"></el-input-number>
                        </el-form-item>
                        <el-form-item label="高度">
                            <el-input-number v-model="ruleFormset.log.height"></el-input-number>
                        </el-form-item>
                        <el-form-item label="列数">
                            <el-input-number v-model="ruleFormset.log.col"></el-input-number>
                        </el-form-item>
                        <el-form-item label="显示位置">
                            <el-radio-group v-model="ruleFormset.log.Container">
                                <el-radio label="left">left</el-radio>
                                <el-radio label="center">center</el-radio>
                                <el-radio label="right">right</el-radio>
                                <el-radio label="bottom">bottom</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否显示">
                            <el-switch v-model="ruleFormset.log.show" />
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="学生使用详情">
                    <el-col :span="24">
                        <el-form-item label="排序">
                            <el-input-number v-model="ruleFormset.table.index"></el-input-number>
                        </el-form-item>
                        <el-form-item label="宽度">
                            <el-input-number v-model="ruleFormset.table.width"></el-input-number>
                        </el-form-item>
                        <el-form-item label="高度">
                            <el-input-number v-model="ruleFormset.table.height"></el-input-number>
                        </el-form-item>
                        <el-form-item label="列数">
                            <el-input-number v-model="ruleFormset.table.col"></el-input-number>
                        </el-form-item>
                        <el-form-item label="显示位置">
                            <el-radio-group v-model="ruleFormset.table.Container">
                                <el-radio label="left">left</el-radio>
                                <el-radio label="center">center</el-radio>
                                <el-radio label="right">right</el-radio>
                                <el-radio label="bottom">bottom</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="是否显示">
                            <el-switch v-model="ruleFormset.table.show" />
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="设备列表">
                    <el-row v-for="v in ruleFormset.list">
                        <el-col :span="24">
                            <el-form-item label="设备">
                                <el-select v-model="v.name" disabled>
                                    <el-option v-for="item in list" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="控制排序">
                                <el-input-number :model-value="999" v-model="v.conindex"></el-input-number>
                            </el-form-item>
                            <el-form-item label="排序">
                                <el-input-number v-model="v.index"></el-input-number>
                            </el-form-item>

                            <el-form-item label="宽度">
                                <el-input-number v-model="v.width"></el-input-number>
                            </el-form-item>
                            <el-form-item label="高度">
                                <el-input-number v-model="v.height"></el-input-number>
                            </el-form-item>
                            <el-form-item label="列数">
                                <el-input-number v-model="v.col"></el-input-number>
                            </el-form-item>
                            <el-form-item label="显示位置">
                                <el-radio-group v-model="v.Container">
                                    <el-radio label="left">left</el-radio>
                                    <el-radio label="center">center</el-radio>
                                    <el-radio label="right">right</el-radio>
                                    <el-radio label="bottom">bottom</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item label="是否显示">
                                <el-switch v-model="v.show" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form-item>

            </el-form>

            <div class="row">
                <div class="col text-right">
                    <el-button @click="dialogVisible2 = false">取 消</el-button>
                    <el-button type="primary" @click="submit">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ElMessage } from "element-plus";
import { toLocaleDateString } from "../../../util/time";
import {
    asyncgettuyaorganize,
    asynccreateaorganize,
} from "../../../api/index";
import { computed, onMounted, ref, watch } from "vue";
import TuyaiotModel from "../../../mysql_interface/tuyaiotmodel";
import { assign } from "lodash-es";
import { DeviceServiceDetailResult, Icategory, HOME } from "../../../tuyav2/interface";







const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const sortable = ref<"DESC" | "ASC">("DESC");
const limit = ref(20);
const offset = ref(0);
const order = ref<keyof TuyaiotModel.ITorganize>("ID");
const like = ref("");
const title = ref("添加");
const ruleForm = ref<TuyaiotModel.ITorganize>(assign({}))
const tableData = ref<TuyaiotModel.ITorganize[]>([]);
const count = ref(0)

onMounted(() => {
    start()
})

function addvideo(str: string) {
    if (!ruleFormset.value) {
        ruleFormset.value = {
            video: [],
            char: [],
            table: {
                index: 2,
                name: 'table',
                show: true,
                col: 12
            },
            overview: {
                index: 3,
                name: 'overview',
                show: true,
                col: 8
            },
            percentage: {
                index: 2,
                name: 'percentage',
                show: true,
                col: 8
            },
            log: {
                index: 5,
                name: 'log',
                show: true,
                col: 12
            },
            list: [],
            // title: "",
            // logo: ""
        }
    }
    if (str === 'video') {
        ruleFormset.value.video.push({
            index: 1,
            name: '',
            show: true,
            col: 12
        })
    } else if (str === 'char') {
        ruleFormset.value.char.push({
            index: 1,
            name: '',
            show: true,
            col: 12
        })
    }

}

function removevideo(str: string) {
    if (ruleFormset.value) {
        if (str === 'video') {
            ruleFormset.value.video.pop()

        } else if (str === 'char') {
            ruleFormset.value.char.pop()
        }
    }
}

type Iv2set = NonNullable<TuyaiotModel.ITorganize['v2set']>

const ruleFormset = computed<Iv2set>({
    get() {
        return assign({
            left: 0,
            right: 0,
            video: [],
            char: [],
            team_id: [],
            table: {
                index: 2,
                name: 'table',
                show: true,
                col: 12
            },
            overview: {
                index: 3,
                name: 'overview',
                show: true,
                col: 8
            },
            percentage: {
                index: 2,
                name: 'percentage',
                show: true,
                col: 8
            },
            log: {
                index: 5,
                name: 'log',
                show: true,
                col: 12
            },
            list: [],
            title: "",
            logo: ""
        }, ruleForm.value.v2set)
    },
    set(e) {
        console.log(e)
        ruleForm.value.v2set = e
    }
})


const tuyastate = ref<Icategory[]>([])

async function start() {
    try {
        let z: [keyof TuyaiotModel.ITorganize, any] | undefined;
        if (like.value) {
            z = ["name", like.value];
        }
        const data = await asyncgettuyaorganize({
            _limit: limit.value,
            _offset: offset.value,
            _order: order.value,
            _sortable: sortable.value,
            _like: z,

        });
        tableData.value = data.rows;
        count.value = data.count;
        fetch('https://cdn.hterobot.com/json/tuyastatev2.json').then(c => {
            return c.json()
        }).then((c: { category: Icategory[] }) => {
            tuyastate.value = c.category
        })
    } catch (e: any) {
        ElMessage.error(e);
    }
}
function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
}

function handleClick(row: TuyaiotModel.ITorganize) {
    title.value = "修改";
    ruleForm.value = JSON.parse(JSON.stringify(row));
    dialogVisible.value = true;
    homelist.value = []
    fetch('/api/security/iot', {
        body: JSON.stringify({
            type: 'users.homes',
            name: String(row.name)
        }),
        cache: 'no-cache',
        headers: {
            'content-type': 'application/json',
        },
        method: 'POST',
    }).then(c => c.json()).then(z => {
        console.log(z)
        if (Array.isArray(z.result)) {
            homelist.value = z.result
        } else {
            ElMessage.error('没有查询到')
        }

    })
}

const list = ref<DeviceServiceDetailResult[]>([])

const homelist = ref<HOME>([])

async function v2set(row: TuyaiotModel.ITorganize) {
    if (!row.home_id?.length) {
        ElMessage.error('请设置家庭')
        return
    }
    await fetch('/api/security/iot', {
        body: JSON.stringify({
            type: 'homes.devices',
            name: String(row.name)
        }),
        cache: 'no-cache',
        headers: {
            'content-type': 'application/json',
        },
        method: 'POST',
    }).then(d => d.json()).then((_data: { result: { list: DeviceServiceDetailResult[] }, success: boolean, message: string }[]) => {
        const _list = []
        for (const data of _data) {
            if (data.success) {
                for (const z of data.result) {
                    const f = _list.findIndex(c => c.id === z.id)
                    if (f === -1) {
                        _list.push(z)
                    }
                }
            }
        }
        list.value = _list
        ruleForm.value = row
        if (!ruleForm.value.v2set) {
            ruleForm.value.v2set = {
                left: 0,
                right: 0,
                video: [],
                char: [],
                table: {
                    index: 2,
                    name: 'table',
                    show: true,
                    col: 12
                },
                overview: {
                    index: 3,
                    name: 'overview',
                    show: true,
                    col: 8
                },
                percentage: {
                    index: 2,
                    name: 'percentage',
                    show: true,
                    col: 8
                },
                log: {
                    index: 5,
                    name: 'log',
                    show: true,
                    col: 12
                },
                list: [],
                title: "",
                logo: ""
            }
        }
        ruleForm.value.v2set.list = list.value.map(e => {
            const n = ruleForm.value.v2set?.list.find(c => c.name === e.id)
            if (n) {
                return n
            }
            return {
                index: 999,
                name: e.id,
                show: true,
                col: 8
            }
        })
        dialogVisible2.value = true
    }).catch(f => {
        console.log(f)
        ElMessage.error(f)
    })
}

function sortchange(row: any) {
    const { prop, order } = row;
    if (order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    order.value = prop;
}
function formatter(updatedAt: string) {
    return toLocaleDateString(updatedAt);
}

async function submit() {
    try {
        await asynccreateaorganize(ruleForm.value);
        ElMessage({
            message: "添加成功",
            type: "success",
        });
        start();
        dialogVisible.value = false;
        dialogVisible2.value = false;
    } catch (e: any) {
        ElMessage({
            message: e,
            type: "error",
        });
    }
}

</script>

<style scoped>
.demo-ruleForm {
    height: 60vh;
    overflow: scroll;
}
</style>